<!doctype html>
<!--[if lt IE 7 ]> <html lang="en" class="ie6"> <![endif]-->
<!--[if IE 7 ]>    <html lang="en" class="ie7"> <![endif]-->
<!--[if IE 8 ]>    <html lang="en" class="ie8"> <![endif]-->
<!--[if IE 9 ]>    <html lang="en" class="ie9"> <![endif]-->
<!--[if !IE]><!--> <html lang="en"> <!--<![endif]-->
<head>
	<meta charset="utf-8" />
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
	<meta name="renderer" content="webkit" />
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
	<script type="text/javascript" src="book/third/jquery.min.1.7.js"></script>
	<script type="text/javascript" src="book/js/turn.min.js"></script>
	<script type="text/javascript" src="highlight.min.js"></script>
	<link rel="stylesheet" href="atom-one-dark.min.css" />
	<link rel="stylesheet" href="book/css/main.css" />
	<link rel="stylesheet" href="book/css/book.css" />
	<style>
	.page-wrapper { top: 0px !important; }
	.shadow { visibility: hidden; }
	body { background: black; }
	.sj-book .p1 { background-image: none !important; }
	#test-container { width: 410px; height: 520px; position: relative; background: #FFFFFF; overflow-x: hidden; overflow-y: scroll; }
	#mainContainer { display: none; position: absolute; top: 0; right: 0; left: 0; bottom: 0; overflow-x: hidden; overflow-y: auto; word-wrap: break-word; background: white; }
	#canvas { display: none; }
	</style>
</head>
<body>
	<div id="canvas">
		<div id="book-zoom">
			<div class="sj-book">
				<div class="own-size page odd" style="width: 460px; height: 582px; float: left; position: absolute; inset: 0px auto auto 0px; transform-origin: 0% 0%;">
					<div class="book-content-container" style="background:white;">
						<div id="test-container">
						</div>
					</div>
				</div>
				<span class="page-number">1</span>
			</div>
		</div>
	</div>
	<div id="mainContainer">
	</div>
	<script type="text/javascript">
	function post(url, data, callback) {
		const ajax = new XMLHttpRequest();
		ajax.open( 'post' , url , true );
		ajax.setRequestHeader('Content-Type', 'application/json');
		ajax.onreadystatechange = function () {
			if (ajax.readyState == 4 && ajax.status == 200) {
				console.log(url, 'post success');
				callback && callback(ajax.responseText);
			}
		}
		ajax.send(JSON.stringify(data));
	}
	function getPages(children, pageIndex, offsetTop, offsetHeight) {
		const boxHeight = 520;
		const container = $('#test-container')[0];
		const pages = [];
		let pageSize = 20;
		let lastStartIndex = -1;
		let startIndex = 0;
		let offset = 0;
		let count = 0;
		const totalCount = children.length;
		while (startIndex < totalCount) {
			let list;
			while(1) {
				list = children.slice(startIndex, startIndex+pageSize);
				container.innerHTML = getHtml(list);
				container.scrollTo(0, offset-offsetTop);
				count = list.length;
				const lastEl = $(`#item${count-1}`)[0];
				if (lastEl.offsetTop + lastEl.offsetHeight > boxHeight + offset || startIndex + pageSize >= totalCount) {
					break;
				}
				pageSize += 20;
			}
			pageSize = 20;

			let i = 0;
			const page = [];
			while (1) {
				if (i === count) {
					startIndex += i;
					break;
				}
				const child = children[startIndex+i];
				const el = $(`#item${i}`)[0];
				const lineHeight = child.lineHeight || 14;
				pageIndex && console.log("======="+(startIndex+i)+":", { name: `item${i}`, text: list[i].table ? 'table' : list[i].code ? 'code' : list[i].images ? 'img' : (list[i].text||'').slice(0,5), offsetTop: el.offsetTop, offsetHeight: el.offsetHeight, offset, boxHeight });
				if (el.offsetTop + el.offsetHeight > boxHeight + offset) {
					pageIndex && console.log("=======endout:", { lastStartIndex, startIndex: startIndex+i });
					if (lastStartIndex === startIndex+i) {
						pageIndex && console.log("[holepage]:", { i: startIndex+i, t: -offset, h: boxHeight });
						page.push({ i: startIndex+i, t: -offset, h: boxHeight });
						offset += boxHeight;
					} else {
						const partHeight = boxHeight + offset - el.offsetTop;
						pageIndex && console.log("=======endin:", {i: startIndex+i, partHeight, lineHeight});
						let oldOffset = offset;
						if (partHeight >= lineHeight) {
							const line = Math.floor(partHeight / lineHeight);
							offset = line * lineHeight;
							pageIndex && console.log("[endpage split]:", { name: `item${i}`, partHeight, offsetTop: el.offsetTop, offset, oldOffset, h: el.offsetTop + offset - oldOffset, line });
							page.push({ i: startIndex+i, h: el.offsetTop + offset - oldOffset });
						} else {
							offset = 0;
							pageIndex && console.log("[endpage]:", { name: `item${i}`, partHeight, offsetTop: el.offsetTop, oldOffset, h: el.offsetTop - oldOffset });
							page.push({ i: startIndex+i, h: el.offsetTop - oldOffset });
						}
					}
					startIndex += i;
					lastStartIndex = startIndex;
					break;
				}
				pageIndex && console.log("[page]:", { name: `item${i}`, i: startIndex+i, t: offset ? -offset : 0 });
				page.push({ i: startIndex+i, t: offset ? -offset : 0 });
				i++;
			}
			pages.push(page);

			if (pageIndex > 0 && pages.length >= pageIndex) {
				container.style.height = `${page[page.length-1].h+offsetHeight}px`;
				console.log("=======pages:", pages);
				return;
			}
		}
		if (pageIndex <= 0) {
			console.log("=======pages:", pages);
			return;
		}
		const pageCount = pages.length;
		post('/setBook', pages, ()=>{
			if (<%build%>) {
				post('/build', { pageCount: (pageCount%2 ? pageCount+1 : pageCount)+4, realPageCount: pageCount }, result => document.write(result));
			} else {
				window.location.href = '/main.html?pageCount='+((pageCount%2 ? pageCount+1 : pageCount)+4);
			}
		});

		return pages;
	}
	function getHtml(children) {
		let imgNo = 1;
		return children.map((o, i)=>{
			if (o.headingNo) {
				return `<h${o.headingNo} id="item${i}" style="font-size: ${o.fontSize}px;">${o.text}</h${o.headingNo}>`;
			} else if (o.images) {
				return `<div id="item${i}" class="imageRow" style="width:${o.w}px;height:${o.h}px;">${o.images.map(m=>`<div class="imageItem"><img src="${m.img}" style="width:${m.w}px;height:${m.h}px;"/>${m.text?`<div class="imageItem">图${imgNo++}：${m.text}</div>`:''}</div>`).join('')}</div><br/>`;
			} else if (o.table) {
				return `<table id="item${i}"><thead><tr>${o.table.header.map(m=>`<th style="text-align:${m.alignment};min-width:${m.width}px;max-width:${m.width}px">${m.text}</th>`).join('')}</tr></thead><tbody>${o.table.rows.map(m=>`<tr>${m.map(n=>`<td style="text-align:${n.alignment}">${n.text}</td>`).join('')}</tr>`).join('')}</tbody></table>`;
			} else if (o.code) {
				return `<pre id="item${i}"><code class="hljs">${hljs.highlight(o.languageName, o.code).value}</code></pre>`;
			} else {
				return `<p id="item${i}" style="font-size: ${o.fontSize}px; line-height: ${o.lineHeight}px;">&emsp;&emsp;${o.text}</p>`;
			}
		}).join('');
	}
	function loadApp() {
		var flipbook = $('.sj-book');

		// Flipbook
		flipbook.turn({
			elevation: 50,
			autoCenter: true,
			gradients: true,
			duration: 1000,
			pages: 1,
		});
		flipbook.addClass('animated');
		var pageIndex = <%pageIndex%>;
		var offset = '<%o%>';
		var offsetTop = 0;
		var offsetHeight = 0;
		if (offset !== 'undefined') {
			var list = offset.split(/,|，/);
			offsetTop = +list[0] || 0;
			offsetHeight = (+list[1] || 0)+offsetTop;
		}
		// Show canvas
		if (pageIndex != undefined) {
			$('#canvas').css({visibility: ''});
		}
		setTimeout(()=>{
			getPages(children, pageIndex, offsetTop, offsetHeight);
		}, 50);
	}
	const children = <%children%>;

	// 如果宽度小于700，则使用文档显示
	if (window.screen.width <= 700) {
		$('#mainContainer').css({display: 'block'});
		$('#mainContainer').html(getHtml(children));
	} else {
		$('#canvas').css({display: 'block', visibility: 'hidden'});
		loadApp();
	}
</script>
</body>
</html>
